//
//  WBNetworkTool.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/7.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit
import AFNetworking

class WBNetworkTool: AFHTTPSessionManager {
    /// swift中单例的标准写法
    //static let shared: WBNetworkTool = WBNetworkTool()
    static let shared: WBNetworkTool = {
        let tool = WBNetworkTool(baseURL: nil)
        tool.responseSerializer.acceptableContentTypes? = ["application/json", "text/json", "text/javascript", "text/html", "text/plain"]
        
        return tool
    }()
    
    /// 网络中间层的接口
    ///
    /// - Parameters:
    ///   - urlStr: url的字符串
    ///   - method: 请求方式
    ///   - parameters: 参数， 可以传nil，所以也是一个可选值
    ///   - callBack: 完成回调, 有参数，无反回值的闭包。参数就是从服务器获取的数据，数据有可能获取不成功，所以应该是一个可选值
    func request(urlStr: String,
                 method: String,
                 parameters: Any?,
                 callBack: @escaping (Any?)->()) {
        if method == "GET" {
            self.get(urlStr, parameters: parameters, headers: nil, progress: nil, success: { (_, responseObject) in
                //将AFN获取的数据原封不动地回传给调用者
                callBack(responseObject)
            }, failure: { (_, error) in
                print(error)
                //如果失败，回传nil，告诉调用者获取数据失败
                callBack(nil)
            })
        } else if method == "POST" {
            self.post(urlStr, parameters: parameters, headers: nil, progress: nil, success: { (_, responseObject) in
                callBack(responseObject)
            }, failure: { (_, error) in
                print(error)
                callBack(nil)
            })
        }
    }
}









